package com.hdoit.ares.web.wechat;



import java.util.Date;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

import org.springframework.util.StringUtils;

import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.tennetcn.common.aop.CommonApplicationContextUtil;
import com.tennetcn.common.enums.BaseEnumConstant;
import com.tennetcn.common.logical.wechat.model.WechatOperateLog;
import com.tennetcn.common.logical.wechat.service.IWechatOperateLogService;
import com.tennetcn.common.selfcommon.enums.wechat.WechatOperateType;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.wechat.WechatManager;

public class WechatTemplateManager{
	
	/*private final String url = "www.putiyoli.net/ares/wechat/acc/redEnvelope/redEnvelopeIndex";
	
	private final String testUrl = "www.hdoit.com/ares/wechat/acc/redEnvelope/redEnvelopeIndex";*/

	/**
	 * 订单支付成功通知
	 */
	public static String sendOrderPaySuccess(String openId, double totalFee, String name,String id) {
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(openId);
		templateMessage.setTemplateId(MsgTemplate.orderPaySuccess);
		templateMessage.getData().add(new WxMpTemplateData("first", "恭喜您，支付成功", MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("orderMoneySum", "【" + totalFee + "】", MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("orderProductName", name, MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("Remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));
		
		if(!StringUtils.isEmpty(id)){
			String url = "www.putiyoli.net/ares/wechat/acc/redEnvelope/redEnvelopeIndex?id="+id;
   		 	templateMessage.setUrl(url);
   		 	templateMessage.getData().add(new WxMpTemplateData("Remark", "点击详情领取红包,红包将于7天后过期", MsgTemplate.msgRedColor));
		}
		
		Customer customer=new Customer();
		customer.setOpenId(openId);
		return sendTemplateToWechat(templateMessage,customer);
	}
	
	/**
	 * 加入会员通知
	 * openId是发送给谁的openId，currentCustomer是当前加入的人，level是游客，refereeCustomer是二代分享
	 * 
	 */
	public static String sendUpdateLevel(String openId, Customer currentCustomer,String level,Customer refereeCustomer,String id) {
		String levelStr=BaseEnumConstant.getGivenEnumByVlue(CustomerLevel.class,level);
		
		//是游客就取昵称，别的取真实名字
		String username=CustomerLevel.visitor.equals(currentCustomer.getLevel())?currentCustomer.getNickname():currentCustomer.getUsername();
		int userIdentity=currentCustomer.getUserIdentity();
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(openId);
		templateMessage.setTemplateId(MsgTemplate.newVipJoin);
		
		//pre代表前面需要切换的语句，suf代表后面需要切换的语句
		String pre = "您推荐的";
		String suf = "成功加入";
		
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));
		
		//是会员的时候
		if(CustomerLevel.vip.equals(level)){ 
			 suf = "成功注册为";
		}
		
		//判断是发给上一级还是上上一级的
		if(refereeCustomer == null){
			System.err.println("进来了进来了进来了"+currentCustomer.getLevel());
		     templateMessage.getData().add(new WxMpTemplateData("first", "恭喜您，" + pre + "【"+username+"】" + suf + "【"+levelStr+"】，点击进入我的团队查看!", MsgTemplate.msgBlueColor));
		     if(!StringUtils.isEmpty(id)){
		    	 String url = "www.putiyoli.net/ares/wechat/acc/redEnvelope/redEnvelopeIndex?id="+id;
	    		 templateMessage.getData().add(new WxMpTemplateData("remark", "点击详情领取红包,红包将于7天后过期", MsgTemplate.msgRedColor));
	    		 templateMessage.setUrl(url);
		     }
		    
		     if(CustomerLevel.visitor.equals(level)){
		    	 String url = "www.putiyoli.net/ares/wechat/acc/myWealth/bonusDetail";
		    	 templateMessage.getData().add(new WxMpTemplateData("remark", "成功邀请新人加入平台，奖励您5个金豆，点击查看详情", MsgTemplate.msgRedColor));
		    	 templateMessage.setUrl(url);	 
		     }
		}else{
			//上一级是初创的时候
			if(CustomerLevel.maker.equals(refereeCustomer.getLevel())){
				pre = "您的初创";
			}
			
			//上一级是高创的时候
            if(CustomerLevel.highMaker.equals(refereeCustomer.getLevel())){
            	pre = "您的高创";
			}
			
            templateMessage.getData().add(new WxMpTemplateData("first", "恭喜您，" + pre + "【"+refereeCustomer.getUsername()+"】" +
            "推荐的【"+username+"】" + suf + "【"+levelStr+"】，点击进入我的团队查看!", MsgTemplate.msgBlueColor));
            
            templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));
		}
		
		templateMessage.getData().add(new WxMpTemplateData("keyword1", "【" + userIdentity + "】", MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtils.convertDate2String(DateUtils.DATETIME_FORMAT, DateUtils.getCurrent()), MsgTemplate.msgBlueColor));
		

		return sendTemplateToWechat(templateMessage,currentCustomer);
	}

	/**
	 *	关注成功通知 
	 */
	public static String sendAttentionSuccess(String openId, Customer customer) {
		// 回复本人的关注消息
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(openId);
		templateMessage.setTemplateId(MsgTemplate.attentionSuccess);
		templateMessage.getData().add(new WxMpTemplateData("first", "恭喜您【" + customer.getUserIdentity() + "】，已经加入普天永利", MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1", "【" + customer.getNickname() + "】", MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2", DateUtils.convertDate2String(DateUtils.DATETIME_FORMAT, DateUtils.getCurrent()), MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));

		return sendTemplateToWechat(templateMessage,customer);
	}
	
	
	/**
	 * 每日奖金收入提醒
	 */
	public static String sendAwardMoney(String money,Date currentTime,Customer customer){
		
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(customer.getOpenId());
		templateMessage.setTemplateId(MsgTemplate.awardPaySuccess);
		templateMessage.getData().add(new WxMpTemplateData("first","您今天的奖金收入为【"+money+"】元",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1","奖金",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2",money+"元",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtils.convertDate2String(DateUtils.DATE_FORMAT,currentTime),MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));
		templateMessage.setUrl("www.putiyoli.net/ares/wechat/acc/myWealth/pushBillBonusList?custId="+customer.getId()+"&Endtime="+currentTime);
		
		return sendTemplateToWechat(templateMessage,customer);
	}
	
	/**
	 * 每日金豆收入提醒
	 */
	public static String sendGoldBean(String goldBean,Date currentTime,Customer customer){
		System.err.println("打打打打打打打豆浆奥多久哦阿吉豆骄傲的奇偶街道骄傲的就哦啊叫都叫傲娇");
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(customer.getOpenId());
		templateMessage.setTemplateId(MsgTemplate.awardPaySuccess);
		templateMessage.getData().add(new WxMpTemplateData("first","您今天的金豆收入为【"+goldBean+"】金豆",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1","金豆",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2",goldBean+"金豆",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtils.convertDate2String(DateUtils.DATE_FORMAT,currentTime),MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark", "普天永利，让创业更简单", MsgTemplate.msgBlueColor));
		templateMessage.setUrl("www.putiyoli.net/ares/wechat/acc/myWealth/pushBillGoldBean?custId="+customer.getId()+"&Endtime="+currentTime);
		
		return sendTemplateToWechat(templateMessage,customer);
		
	}
	
	/**
	 * 报价成功提醒
	 */
	public static String sendTomeasure(String insuName,String carLicenseNo,String totalMoney,Date currentTime,Customer customer,String id){
		WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
		templateMessage.setToUser(customer.getOpenId());
		templateMessage.setTemplateId(MsgTemplate.tomeasureSuccess);
		templateMessage.getData().add(new WxMpTemplateData("first","您的报价订单已出炉",MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword1",insuName,MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword2",carLicenseNo,MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword3",totalMoney,MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("keyword4",DateUtils.convertDate2String(DateUtils.DATE_FORMAT,currentTime),MsgTemplate.msgBlueColor));
		templateMessage.getData().add(new WxMpTemplateData("remark","该测算信息只支持一次查看",MsgTemplate.msgRedColor));
		//templateMessage.setUrl("www.putiyoli.net/ares/wechat/acc/myWealth/pushBillGoldBean?custId="+customer.getId()+"&Endtime="+currentTime);
		templateMessage.setUrl("www.hdoit.com/ares/wechat/zzb/tomeasure?id="+id);
		
		return sendTemplateToWechat(templateMessage,customer);
	}
	
	
	/**
	 *	防止失败，多次尝试发送 
	 */
	private static String sendTemplateToWechat(WxMpTemplateMessage templateMessage,Customer customer){
		System.out.println("要发送的消息模板：");
		System.out.println(JsonUtils.toJson(templateMessage));
		WxMpService wxMpService = WechatManager.getInstance().getWxMpService();
		WxMpTemplateMsgService templateMsgService = wxMpService.getTemplateMsgService();
		//消息发送尝试
		//这种时候一般是我们请求微信服务器的时候没有成功，所以这里做三次尝试
		//当然还有就是到了微信，微信发送失败的情况，这个重试就在微信的回调事件里面了
		int count=0;
		String sendResultId=null;
		do{
			try {
				saveWechatOperateLog(customer,templateMessage,"sending");
				sendResultId=templateMsgService.sendTemplateMsg(templateMessage);
				if(!StringUtils.isEmpty(sendResultId)){
					count=3;
				}
				saveWechatOperateLog(customer,templateMessage,sendResultId);
			} catch (WxErrorException e) {
				e.printStackTrace();
			}
			count++;
		}while(count<3);
		
		return sendResultId;
	}
	
	
	private static boolean saveWechatOperateLog(Customer customer,WxMpTemplateMessage templateMessage,String resultType){
		WechatOperateLog wechatOperateLog=new WechatOperateLog();
		wechatOperateLog.setId(CommonUtils.getKeyId());
		wechatOperateLog.setOpenId(customer.getOpenId());
		wechatOperateLog.setOperateDate(DateUtils.getCurrent());
		wechatOperateLog.setUserId(customer.getId());
		wechatOperateLog.setUsername(customer.getUsername());
		wechatOperateLog.setOperateType(WechatOperateType.sendTemplateMessage);
		wechatOperateLog.setBusId(templateMessage.getTemplateId());
		wechatOperateLog.setOperateResult(resultType);
		wechatOperateLog.setContextData(JsonUtils.toJson(templateMessage));
		
		IWechatOperateLogService wechatOperateLogService= getWechatOperateLogService();
		if(wechatOperateLogService==null){
			return false;
		}
		return wechatOperateLogService.addModel(wechatOperateLog);
	}
	
	private static IWechatOperateLogService getWechatOperateLogService(){
		return CommonApplicationContextUtil.getCurrentContext().getBean(IWechatOperateLogService.class);

	}


	
	
}
